﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Widgetsphere.WebUtils
{
	public static class FTPHelper
	{
		public static void UploadFile(string remoteURI, string userName, string password, string ftpFolder, string ftpFile, string localFile)
		{
			// String array to hold the full path of each file to be transfered
			// to the FTP site.
			string[] uploadFiles = { localFile };

			// Create the FTP client
			var ftpClient = new WebClient();

			// The user name and password are stored here
			var nc = new NetworkCredential(userName, password);
			ftpClient.Credentials = nc;

			// used to check if there were any errors in transfering the files
			Exception err = null;

			for (var idx = 0; idx < uploadFiles.Length; idx++)
			{
				// Call the function to transfer the files to the FTP site
				err = Transfer(ftpClient, remoteURI + ftpFolder, ftpFile, uploadFiles[idx]);
				// Check to see if there were any errors in the transfer
				if (err != null)
				{
					// Write the error somewhere and reset err to null for the next transfer
					throw new Exception(
						"Remote folder: " + remoteURI + ftpFolder + "\n" +
						"Remote file: " + ftpFile + "\n" +
						"Local file: " + uploadFiles[idx] + "\n", 
						err						
						);
				}
			}

		}

		private static Exception Transfer(WebClient client, string remoteFolder, string remoteFile, string localFile)
		{
			Exception retErr = null;
			// Get the file name from the local file to name the file on the remote
			//string filename = Path.GetFileName(localFile);

			// Add the file name that the file will be called on the FTP site.
			var WebResources = remoteFolder + remoteFile;
			try
			{
				// Transfer the file to the FTP site.
				client.UploadFile(WebResources, localFile);
			}
			catch (Exception ex)
			{
				// If any errors occurred report it to the caller.
				retErr = ex;
			}
			return retErr;
		}      

	}
}
